import {types, getEnv, applySnapshot, getSnapshot} from 'mobx-state-tree';
import {PageStore} from './Page';
import {when, reaction} from 'mobx';


export interface IPage {
  id: string;
  appDsgnId: string;
  formDsgnId: string;
  label: string;
  path: string;
  icon?: string;
  schema?: any;
}


export const MainStore = types
  .model('MainStore', {
    pages: types.optional(types.array(PageStore), []),
    theme: 'cxd',
    asideFixed: true,
    asideFolded: false,
    offScreen: false,
    addPageIsOpen: false,
    preview: false,
    isMobile: false,
    schema: types.frozen()
  })
  .views(self => ({
    get fetcher() {
      return getEnv(self).fetcher;
    },
    get notify() {
      return getEnv(self).notify;
    },
    get alert() {
      return getEnv(self).alert;
    },
    get copy() {
      return getEnv(self).copy;
    }
  }))
  .actions(self => {
    function toggleAsideFolded() {
      self.asideFolded = !self.asideFolded;
    }

    function toggleAsideFixed() {
      self.asideFixed = !self.asideFixed;
    }

    function toggleOffScreen() {
      self.offScreen = !self.offScreen;
    }

    function setAddPageIsOpen(isOpened: boolean) {
      self.addPageIsOpen = isOpened;
    }

    function addPage(data: IPage, resId: string) {
      self.pages.push(
        PageStore.create({
          ...data,
          id: `${resId}`
        })
      );
    }

    function updatePageSchemaById(schema: any, resId: string) {
      let page = self.pages.find(p => p.id == resId);
      if (page) {
        page.updateSchema(schema);
      }
    }

    function getPageByResId(resId: string) {
      return self.pages.find(p => p.id == resId);
    }

    // function removePageAt(index: number) {
    //   self.pages.splice(index, 1);
    // }

    // function updatePageSchemaAt(index: number) {
    //   self.pages[index].updateSchema(self.schema);
    // }
    function setPageSchemaById(pageId: string, schema: any) {
      self.schema = schema;
    }

    function updateSchema(value: any) {
      self.schema = value;
    }

    function setPreview(value: boolean) {
      self.preview = value;
    }

    function setIsMobile(value: boolean) {
      self.isMobile = value;
    }

    return {
      toggleAsideFolded,
      toggleAsideFixed,
      toggleOffScreen,
      setAddPageIsOpen,
      addPage,
      getPageByResId,
      // removePageAt,
      // updatePageSchemaAt,
      updatePageSchemaById,
      updateSchema,
      setPreview,
      setIsMobile,
      afterCreate() {
        // persist store
        if (typeof window !== 'undefined' && window.localStorage) {
          const storeData = window.localStorage.getItem('store');
          if (storeData) applySnapshot(self, JSON.parse(storeData));

          reaction(
            () => getSnapshot(self),
            json => {
              window.localStorage.setItem('store', JSON.stringify(json));
            }
          );
        }
      }
    };
  });

export type IMainStore = typeof MainStore.Type;
